import { Command } from '@tauri-apps/api/shell'
import { writeTextFile, removeFile } from '@tauri-apps/api/fs'

import { resolveResource } from '@tauri-apps/api/path';

/**
 * 运行 CMD 命令
 * @param cmd 命令
 * @returns
 */
export const runCmd = async (cmd: string) => {
  const options = {}
  return await new Command('powershell', ['-Command', cmd], options).execute()
}

/**
 * 检查文件是否包含音频
 * @param filePath 文件路径
 * @returns
 */
export const hasAudio = async (filePath: string) => {
  const resource = await resolveResource('bin');
  const options = { env: { path: resource } };

  // 获取是否有音频
  let result  = await new Command('ffprobe', ['-i', filePath,'-show_streams', '-select_streams', 'a', '-of', 'json', '-loglevel', 'error'], options).execute();

  if (result.code !== 0) {
    return { code: -1, message: result.stderr };
  }
  const audilInfo = JSON.parse(result.stdout.trim());

  if (audilInfo.streams.length == 0) {
    return { code: 0, message: '无音频流' };
  }
  // 获取音轨静音段信息
  result = await new Command('ffmpeg', ['-i', filePath, '-hide_banner', '-af', 'silencedetect=noise=-30dB:d=1', '-vn', '-sn', '-dn', '-f', 'null', 'NUL'], options).execute()
  if (result.code !== 0) {
    return { code: -1, message: result.stderr };
  }

  const startRows = result.stderr.trim().split("\r\n").filter(row => row.indexOf('silence_start:') != -1);
  if (startRows.length !== 1) {
    return { code: 1, message: '非静音' };

  }

  // 取音频开始值
  const val = startRows[0].split('silence_start:').pop()?.trim();

  if (!val) {
    return { code: -1, message: '音频值处理无效' }
  }
  const startTime = parseFloat(val);
  if (startTime >= 1) {
    return { code: 1, message: '非静音' };
  }
  return { code: 0, message: '静音' };
}

export const concatVideoToMP3 = async (fileList: string[], savePath: string) => {
  // 写拼接文件
  const contents = fileList.map(item => `file '${item}'`).join('\r\n')
  const concatPath = `${savePath}_tmp_concat`
  await writeTextFile(concatPath, contents, { append: false })
  // 执行拼接命令
  const resource = await resolveResource('bin');
  const options = { env: { path: resource } };
  // ffmpeg -f concat -safe 0 -i concat.txt -vn -f mp3 -acodec libmp3lame -y output.mp3
  await new Command('ffmpeg', ['-f', 'concat', '-safe', '0', '-i', concatPath, '-ac', '2', '-c:a', 'libmp3lame', '-q:a', '4', '-y', savePath], options).execute();
  await removeFile(concatPath);
}
